package com.example.myapplication;

import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

/**
 * 应用使用统计列表适配器
 */
public class AppUsageAdapter extends RecyclerView.Adapter<AppUsageAdapter.ViewHolder> {
    private List<AppUsageInfo> appUsageList;
    private long totalUsageTime;
    private OnItemClickListener onItemClickListener;
    private Context context;
    private PackageManager packageManager;

    public interface OnItemClickListener {
        void onItemClick(AppUsageInfo appUsageInfo);
    }

    public AppUsageAdapter(Context context, List<AppUsageInfo> appUsageList) {
        this.context = context;
        this.appUsageList = appUsageList;
        this.packageManager = context.getPackageManager();
        calculateTotalUsageTime();
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.onItemClickListener = listener;
    }

    public void updateData(List<AppUsageInfo> newAppUsageList) {
        this.appUsageList = newAppUsageList;
        calculateTotalUsageTime();
        notifyDataSetChanged();
    }

    private void calculateTotalUsageTime() {
        totalUsageTime = 0;
        if (appUsageList != null) {
            for (AppUsageInfo appUsageInfo : appUsageList) {
                totalUsageTime += appUsageInfo.getTotalTimeInForeground();
            }
        }
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_app_usage, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        AppUsageInfo appUsageInfo = appUsageList.get(position);
        
        holder.textAppName.setText(appUsageInfo.getAppName());
        
        // 显示使用时间和启动次数
        String usageText = appUsageInfo.getFormattedTime();
        if (appUsageInfo.getLaunchCount() > 0) {
            usageText += " (#" + appUsageInfo.getLaunchCount() + ")";
        }
        holder.textUsageTime.setText(usageText);
        
        // 设置进度条
        float percentage = appUsageInfo.getUsagePercentage(totalUsageTime);
        holder.progressUsage.setProgress((int) percentage);
        
        // 加载应用图标
        loadAppIcon(holder.imgAppIcon, appUsageInfo);
        
        // 设置点击事件
        holder.itemView.setOnClickListener(v -> {
            if (onItemClickListener != null) {
                onItemClickListener.onItemClick(appUsageInfo);
            }
        });
    }
    
    /**
     * 加载应用图标
     */
    private void loadAppIcon(ImageView imageView, AppUsageInfo appUsageInfo) {
        try {
            if (appUsageInfo.getApplicationInfo() != null) {
                Drawable appIcon = packageManager.getApplicationIcon(appUsageInfo.getApplicationInfo());
                imageView.setImageDrawable(appIcon);
            } else {
                // 如果没有应用信息，使用默认图标
                imageView.setImageResource(R.mipmap.ic_launcher);
            }
        } catch (Exception e) {
            // 加载图标失败，使用默认图标
            imageView.setImageResource(R.mipmap.ic_launcher);
        }
    }

    @Override
    public int getItemCount() {
        return appUsageList != null ? appUsageList.size() : 0;
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        ImageView imgAppIcon;
        TextView textAppName;
        TextView textUsageTime;
        ProgressBar progressUsage;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            imgAppIcon = itemView.findViewById(R.id.img_app_icon);
            textAppName = itemView.findViewById(R.id.text_app_name);
            textUsageTime = itemView.findViewById(R.id.text_usage_time);
            progressUsage = itemView.findViewById(R.id.progress_usage);
        }
    }
}
